package club.martaintao.activiti7springbootdemo.controller;

import club.martaintao.activiti7springbootdemo.common.BaseResponse;
import club.martaintao.activiti7springbootdemo.model.vo.TaskVO;
import org.activiti.api.process.model.ProcessInstance;
import org.activiti.api.process.runtime.ProcessRuntime;
import org.activiti.api.runtime.shared.query.Page;
import org.activiti.api.runtime.shared.query.Pageable;
import org.activiti.api.task.model.Task;
import org.activiti.api.task.model.builders.TaskPayloadBuilder;
import org.activiti.api.task.runtime.TaskRuntime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/task")
public class TaskController {

    @Autowired
    TaskRuntime taskRuntime;

    @Autowired
    ProcessRuntime processRuntime;

    @PostMapping("/completeTask/{taskId}")
    public BaseResponse completeTask(@PathVariable String taskId){
        Task task = taskRuntime.task(taskId);
        if (task.getAssignee()==null){
            // 说明任务需要拾取
            taskRuntime.claim(TaskPayloadBuilder.claim().withTaskId(taskId).build());
        }
        taskRuntime.complete(TaskPayloadBuilder.complete().withTaskId(taskId).build());
        return BaseResponse.success();
    }

    @GetMapping("/getTasks")
    public BaseResponse getTasks(){
        Page<Task> taskPage = taskRuntime.tasks(Pageable.of(0, 100));
        List<Task> tasks = taskPage.getContent();
        List<TaskVO> taskVOS = new ArrayList<>();
        for (Task task : tasks) {
            TaskVO taskVO = TaskVO.of(task);
            ProcessInstance instance = processRuntime.processInstance(task.getProcessInstanceId());
            taskVO.setInstanceName(instance.getName());
            taskVOS.add(taskVO);
        }
        return BaseResponse.success(taskVOS);
    }

}
